package com.juyu.miliao.api.util;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.domain.dto.LocationDTO;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xuanqicheng
 */
public class LocationUtil {

    /**
     * 根据经纬度湖区
     * @param url
     * @param key
     * @param location
     * @return
     * @throws Exception
     */
    public static LocationDTO getProvinceAndCity(String url, String key, LocationDTO locationDTO) throws Exception {

        String province = "";
        String city = "";
        Map<String, Object> map = new HashMap<>(4);
        map.put("key",key);
        String location = "";
        if(StringUtils.isNotBlank(locationDTO.getLon())
                &&StringUtils.isNotBlank(locationDTO.getLat())){
            location = locationDTO.getLon()+","+locationDTO.getLat();
        }
        map.put("location", location);
        String result = HttpUtil.doGet(url, map);
        if (StringUtils.isNotBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            String status = json.getString("status");
            if (status != null && "1".equals(status)) {
                JSONObject regeocode = json.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                province = addressComponent.getString("province");

                if (province.startsWith("北京市") || province.startsWith("天津市")
                        || province.startsWith("上海市") || province.startsWith("重庆市")) {
                    city = province;
                } else {
                    city = addressComponent.getString("city");
                }
            }
        }

        locationDTO.setCity(city);
        locationDTO.setProvince(province);
        return locationDTO;
    }

}
